<template>
  <div>
        <van-nav-bar
  title="城市列表"
  left-arrow
   @click-left='backFn'
   fixed:true
   z-index=100000
/>
<van-index-bar :index-list="indexList">
  <van-index-anchor index="#"></van-index-anchor>
  <div class="van-index-anchor">当前城市</div>
  <van-cell index="#"
        title="上海"
        @click="$router.push('/home')" />

    <!-- 热门城市 -->
      <van-index-anchor index="热">热门城市</van-index-anchor>
      <van-cell
        :title="item.label"
        v-for="(item, index) in HotCityList"
        :key="index"
        @click="handleRouter(item, 1)"
      />

       <!-- 城市 -->
      <div v-for="(item, index) in cityListInFirst" :key="index">
        <van-index-anchor :index="index.toUpperCase()">{{
          index.toUpperCase()
        }}</van-index-anchor>
        <van-cell
          :title="city.label"
          v-for="(city, index) in item"
          :key="index"
          @click="handleRouter(city, 2)"
        />
      </div>
</van-index-bar>
 <div class="loading" v-if="showLoading">
      <van-loading size="40px" color="#333333">加载中...</van-loading>
    </div>
  </div>
</template>

<script>
import { getCityList, getHotCity } from '@/api/favorites'
export default {
  name: 'CityPage',
  data () {
    return {
      CityList: [],
      CityNameABC: [],
      arr: [],
      cityListInFirst: {},
      indexList: [],
      HotCityList: [],
      showLoading: true
    }
  },
  async created () {
    // 获取城市列表
    const res = await getCityList({
      level: 1
    })
    console.log(res)
    this.CityList = res.body
    res.body.forEach(item => {
      this.CityNameABC.push(item.short.charAt(0).toUpperCase())
    })
    this.CityNameABC = this.CityNameABC.sort()
    this.arr = Array.from(new Set([...this.CityNameABC]))
    // 城市按A-Z排序
    const CityName = {}
    res.body.forEach((item) => {
      if (CityName[item.short[0]]) {
        CityName[[item.short[0]]].push(item)
      } else {
        CityName[item.short[0]] = [item]
      }
    })
    const NameList = Object.keys(CityName).sort()
    for (let i = 0; i < NameList.length; i++) {
      this.cityListInFirst[NameList[i]] = CityName[NameList[i]]
    }
    NameList.forEach((item, index) => {
      NameList[index] = item.toUpperCase()
    })
    this.indexList = NameList
    this.indexList.unshift('热')
    this.indexList.unshift('#')
    // 获取热门城市
    const abb = await getHotCity()
    console.log(abb.body)
    this.HotCityList = abb.body
  },
  methods: {
    backFn () {
      this.$router.push('/FirstPage')
    }
  }

}
</script>

<style>
.van-nav-bar{
  position: fixed;
  width: 100%;
}

.van-cell{
  height: 70px;
  font-size: 18px;
}
.van-index-bar{
position: absolute;
margin-top: 20px;
}
span{
  margin-bottom: 10px;
}
</style>
